#include "yaml-cpp/yaml.h"
#include <fstream>
#include <iostream>
#include <vector>

int main() {
  // 写入 YAML 文件
  {
    YAML::Emitter emitter;
    emitter << YAML::BeginMap;
    emitter << YAML::Key << "name" << YAML::Value << "John Doe";
    emitter << YAML::Key << "age" << YAML::Value << 30;
    emitter << YAML::Key << "hobbies" << YAML::Value << YAML::BeginSeq;
    emitter << "reading" << "hiking" << "gaming";
    emitter << YAML::EndSeq;
    emitter << YAML::Key << "address" << YAML::Value << YAML::BeginMap;
    emitter << YAML::Key << "city" << YAML::Value << "New York";
    emitter << YAML::Key << "street" << YAML::Value << "5th Avenue";
    emitter << YAML::EndMap;
    emitter << YAML::EndMap;

    std::ofstream fout("test.yaml");
    fout << emitter.c_str();
  }

  // 读取 YAML 文件
  try {
    YAML::Node config = YAML::LoadFile("test.yaml");

    // 读取简单值
    std::string name = config["name"].as<std::string>();
    int age = config["age"].as<int>();

    // 读取数组
    std::vector<std::string> hobbies;
    for (YAML::const_iterator it = config["hobbies"].begin();
         it != config["hobbies"].end(); ++it) {
      hobbies.push_back(it->as<std::string>());
    }

    // 读取嵌套结构
    std::string city = config["address"]["city"].as<std::string>();
    std::string street = config["address"]["street"].as<std::string>();

    // 打印结果
    std::cout << "Name: " << name << std::endl;
    std::cout << "Age: " << age << std::endl;
    std::cout << "Hobbies: ";
    for (const auto &hobby : hobbies) {
      std::cout << hobby << " ";
    }
    std::cout << "\nAddress: " << street << ", " << city << std::endl;

  } catch (const YAML::Exception &e) {
    std::cerr << "YAML Error: " << e.what() << std::endl;
  }

  return 0;
}